{% extends "layout/manage.html" %}
{% load static %}
{% block css %}

    <style>

        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function label {
            padding: 0;
            margin: 0;
        }

        .panel-default > .panel-heading .function input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            height: 20px;
            overflow: hidden;
            z-index: 1003;
        }

        .upload_progress {
            position: fixed;
            right: 2px;
            bottom: 2px;
            width: 400px;
        }

        .upload_error {
            color: red;
        }
    </style>

{% endblock %}

{% block content %}

    <div class="panel panel-default" style="margin-top: 20px">
        <!-- Default panel contents -->
        <div class="panel-heading" style="overflow: hidden;">
            <div class="">
                <a href="{% url 'web:manage:file' project_id=request.tracer.project.id %}">
                    <i class="fa fa-home" aria-hidden="true"></i>
                    <span>文件库</span>
                </a>
                {% for bread_crumb in bread_crumb_list %}
                    <a href="{% url 'web:manage:file' project_id=request.tracer.project.id %}?folder={{ bread_crumb.id }}">
                        <i class="fa fa-caret-right" aria-hidden="true"></i>
                        <span>{{ bread_crumb.name }}</span>
                    </a>
                {% endfor %}
            </div>
            <div class="function">

                <div class="btn btn-primary btn-xs upload" style="position: relative;">
                    <label for="uploadFile"><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</label>
                    <input type="file" multiple name="uploadFile" id="uploadFile">
                </div>
                <a class="btn btn-success btn-xs" data-toggle="modal" data-target="#addModal" data-whatever="新建文件夹">
                    <i class="fa fa-plus-circle" aria-hidden="true"></i>
                    新建文件夹
                </a>

            </div>

        </div>

        <!-- Table -->
        <table class="table">
            <thead>
            <tr>
                <th>名称</th>
                <th>文件大小</th>
                <th>更新者</th>
                <th>更新时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="rowList">
            {% for item in file_object_list %}
                <tr>
                    <td>
                        {% if item.file_type == 1 %}
                            <i class="fa fa-file" aria-hidden="true"></i>
                            {{ item.name }}
                        {% else %}
                            {#                            /*如果是文件夹，则变成a标签，可以点进去*/#}
                            <a href="{% url 'web:manage:file' project_id=request.tracer.project.id %}?folder={{ item.id }}">
                                <i class="fa fa-folder" aria-hidden="true"></i>
                                {{ item.name }}
                            </a>
                        {% endif %}
                    </td>
                    <td>
                        {% if item.file_type == 1 %}
                            {{ item.file_size }}
                        {% else %}
                            -
                        {% endif %}
                    </td>
                    <td>{{ item.update_user.username }}</td>
                    <td>{{ item.update_datetime }}</td>
                    <td>
                        {% if item.file_type == 2 %}
                            <a class="btn btn-default btn-xs" data-toggle="modal" data-target="#addModal"
                               data-whatever="编辑文件夹"
                               data-name="{{ item.name }}"
                               data-fid="{{ item.id }}">
                                <i class="fa fa-edit" aria-hidden="true"></i>
                            </a>
                        {% else %}
                            <a  class="btn btn-default btn-xs download"
                                href="{% url 'web:manage:file_download' project_id=request.tracer.project.id file_id=item.id %}">
                                <i class="fa fa-cloud-download" aria-hidden="true"></i>
                            </a>
                        {% endif %}
                        <a class="btn btn-danger btn-xs" data-toggle="modal" data-target="#alertModal"
                           data-whatever="删除文件夹"
                           data-name="{{ item.name }}"
                           data-fid="{{ item.id }}">
                            <i class="fa fa-trash" aria-hidden="true"></i>
                        </a>
                    </td>
                </tr>
            {% endfor %}

            </tbody>
        </table>
    </div>


    <!-- Modal -->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                </div>
                <div class="modal-body">
                    <form id="form">
                        {% csrf_token %}
                        <input type="text" class="hide" name="fid" id="fid">
                        {% for field in form %}
                            <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                            {{ field }}
                            <span class="error-msg">{{ form.errors.0 }}</span>
                        {% endfor %}
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                    <button id="btnFormSubmit" type="button" class="btn btn-primary">确 定</button>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal 删除文件夹的模态框-->
    <div class="modal fade" id="alertModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         style="margin-top: 100px;text-align: left;">
        <div class="alert alert-danger alert-dismissible fade in" role="alert"
             style="width: 500px; height: 180px; margin: 0 auto">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                    aria-hidden="true">×</span></button>
            <h4>是否确定删除？</h4>
            <p style="padding-top: 20px; padding-bottom: 20px;">文件夹中包含的所有的文件都会被删除！</p>
            <p style="text-align: right;">
                <a type="button" class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">取 消</a>
                <button id="btnDelete" type="button" class="btn btn-danger btn-sm">确 定</button>
            </p>
        </div>
    </div>
    <div id="uploadProgress" class="upload_progress hide">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传进度
            </div>
            <table class="table">
                <tbody id="progressList">

                </tbody>
            </table>
        </div>
    </div>
    <div class="hide">
        <table id="progressTemplate">
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress">
                            <div class="progress-bar progress-bar-primary progress-bar-striped"
                                 role="progressbar" aria-valuenow="0" aria-valuemin="0"
                                 aria-valuemax="100" style="width: 0%;">
                                0%
                            </div>
                        </div>
                    </div>
                    <div class="upload_error"></div>
                </td>
            </tr>
        </table>

    </div>

    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i><span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="update_user"></td>
                <td class="update_datetime"></td>
                <td>
                    <a class="btn btn-default btn-xs download">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>
                    <a class="btn btn-danger btn-xs delete" data-toggle="modal" data-target="#alertModal">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>


{% endblock %}

{% block js %}
    {#    引入cos通过前端上传的js   #}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var FOLDER_URL = "{% url 'web:manage:file' project_id=request.tracer.project.id %}";
        var DELETE_URL = "{% url 'web:manage:file_delete' project_id=request.tracer.project.id %}";

        // 获取临时凭证
        var COS_CREDENTIAL_URL = "{% url 'web:manage:cos_credential' project_id=request.tracer.project.id %}";


        $(function () {
            initModal();
            bindFormSubmit();
            bindDeleteBtn();
            bindUploadFile();
        });

        /* 初始化模态框 */
        function initModal() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var recipient = button.data('whatever'); // Extract info from data-* attributes
                // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
                // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
                var name = button.data("name");
                var fid = button.data("fid");
                var modal = $(this);
                modal.find('.modal-title').text(recipient);
                // 判断是否有fid
                if (fid) {
                    // 有fid表示编辑
                    modal.find("#id_name").val(name);
                    // 对模态框中隐藏的input框赋值，为当前的文件id
                    modal.find("#fid").val(fid);
                } else {
                    // 没有fid则表示新建
                    modal.find('.error-msg').empty();  // 每次访问前清空错误信息
                    $("#form")[0].reset();  // 每次访问前对输入框的内容进行清空
                }


            });

            // 初始化的时候将删除的对话框添加一个属性 fid=传进来的fid
            $('#alertModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var fid = button.data("fid");
                $("#btnDelete").attr("fid", fid);

            })
        }

        /* form表单提交数据 */
        function bindFormSubmit() {
            $("#btnFormSubmit").click(function () {
                $.ajax({
                    url: location.href,
                    method: "POST",
                    data: $("#form").serialize(),
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res);
                        if (res.status) {
                            // 刷新一下
                            location.href = location.href;
                        } else {
                            // 错误信息
                            $.each(res.error, function (key, value) {
                                $("#id_" + key).next().text(value[0]);
                            })
                        }
                    }
                })
            })
        }

        /* 删除文件夹 */
        function bindDeleteBtn() {
            // 发送ajax请求,需要获取删除的文件夹的id
            $("#btnDelete").click(function () {
                $.ajax({
                    url: DELETE_URL,
                    method: "GET",
                    data: {fid: $(this).attr("fid")},
                    success: function (res) {
                        if (res.status) {
                            location.href = location.href
                        }
                    }
                })
            })
        }

        function bindUploadFile() {

            // 绑定一个change()事件
            // 获取临时凭证，可以为临时凭证添加一个有效期，5分钟（获取一次）
            $("#uploadFile").change(function () {
                // 每次上传前清空上传列表
                $("#progressList").empty();
                // 获取要上传的所有文件对象列表
                var fileList = $(this)[0].files;
                // 获取本次要上传的每个文件名称和文件大小
                var checkFileList = [];
                $.each(fileList, function (index, fileObject) {
                    checkFileList.push({"name": fileObject.name, "size": fileObject.size})
                });
                // 把这些数据发送到django后台，Django后台进行容量校验，如果没有问题则返回临时凭证；否则返回错误信息。
                // 将get请求变为post请求，并把checkFileList通过data参数传递到后台
                var cos_object = new COS({
                    getAuthorization: function (options, callback) {
                        // 向django后台发送请求，获取临时凭证
                        // 向/cos/credential/的url发送请求
                        $.post(COS_CREDENTIAL_URL, JSON.stringify(checkFileList),
                            function (res) {
                                if (res.status) {
                                    //
                                    var credentials = res.data && res.data.credentials;
                                    if (!res.data || !credentials) return console.error('credentials invalid');
                                    callback({
                                        TmpSecretId: credentials.tmpSecretId,
                                        TmpSecretKey: credentials.tmpSecretKey,
                                        XCosSecurityToken: credentials.sessionToken,
                                        StartTime: res.data.startTime,
                                        ExpiredTime: res.data.expiredTime,
                                    });
                                    // 上传的时候再显示进度条
                                    $("#uploadProgress").removeClass("hide");
                                } else {
                                    //
                                    alert(res.error);
                                }


                            });
                    }
                });

                // 上传文件，上传文件前先获取临时凭证
                $.each(fileList, function (index, fileObject) {
                    console.log(fileObject.name);
                    var fileName = fileObject.name;
                    var fileSize = fileObject.size;
                    // 进度条相关，找到对应tr进行克隆
                    var tr = $("#progressTemplate").find("tr").clone();
                    // 将文件名添加到name的div中
                    tr.find(".name").text(fileName);
                    // 将tr加到tbody中
                    $("#progressList").append(tr);
                    // key
                    var key = (new Date()).getTime() + "_" + fileName;
                    // 上传文件
                    cos_object.putObject({
                        Bucket: '{{ request.tracer.project.bucket }}', /* 必须 */
                        Region: '{{ request.tracer.project.region }}',     /* 存储桶所在地域，必须字段 */
                        Key: key,              /* 必须  将文件名传入*/
                        StorageClass: 'STANDARD',
                        Body: fileObject, // 上传文件对象
                        onProgress: function (progressData) {
                            // 拿到文件上传的百分比
                            var percent = progressData.percent * 100 + "%";
                            // 对进度条中内容进行修改
                            tr.find(".progress-bar").text(percent);
                            tr.find(".progress-bar").css("width", percent);
                            console.log("文件上传进度--->", fileName, JSON.stringify(progressData));
                        }
                    }, function (err, data) {
                        console.log(err || data);
                        // 走到这里表示上传成功
                        //如果上传成功，则需要将文件相关的数据发送到后台，并存储到数据库中。
                        // data中的数据：{#{statusCode: 200, headers: {…}, Location: "18911075051-1612157922-1304881545.cos.ap-chengdu.m…1%B9%E7%9B%AE%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90", ETag: ""}#}
                        if (data && data.statusCode === 200) {
                            $.post("{% url 'web:manage:file_post' project_id=request.tracer.project.id %}",
                                {
                                    name: fileName,
                                    key: key,
                                    file_size: fileSize,
                                    file_path: data.Location,
                                    parent: {{ parent_object.id}},
                                    {#etag: data.ETag,#}

                                }, function (res) {
                                    console.log(res);
                                    if (res.status) {
                                        var newTr = $("#rowTpl").find("tr").clone();
                                        newTr.find(".name").text(res.data.name);
                                        newTr.find(".file_size").text(res.data.file_size);
                                        newTr.find(".update_user").text(res.data.username);
                                        newTr.find(".update_datetime").text(res.data.datetime);
                                        newTr.find(".delete").attr("data-fid", res.data.id);
                                        newTr.find(".download").attr("href", res.data.download_url);
                                        $("#rowList").append(newTr);
                                        tr.remove()
                                    } else {

                                    }
                                });

                        } else {
                            tr.find(".upload_error").text("上传失败")
                        }


                    });
                })
            })
        }
    </script>
{% endblock %}

